package com.kdtech.analyse.Bbs;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.NumberUtils;
import com.kdtech.utils.StringUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.kdtech.crawler.CrawlHTML;

import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.analyse.AnalyseNews;
/**
 * 联商论坛
 */
public class LinkshopBbsAnalyse implements AnalyseNews{

	
	public boolean isDetailPage(String url){
		boolean bRet = false;
		String[] regex = {
				"http://www.linkshop.com.cn/club/archives/[0-9]{4}/[0-9]*.shtml",
				"http://www.linkshop.com.cn/club/dispbbs.aspx\\?rootid=[0-9]*"
				};
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta bbs = new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt = urlMeta.getHtml();
		String url = urlMeta.getUrl();
		if(!isDetailPage(url)){
		}
		bbs.setUrl(url);
		String title = null;
		String content = null;
		Long date = null;
		String author = null;
		Integer clickNum=0;
		Integer commentNum=0;

		Document doc = Jsoup.parse(htmltxt);
		title = doc.select("h1.ltzd_jiaj").text();
		if(title.contains("主题：")) title = StringUtils.substringAfter(title, "主题：");
		Element firstDiv = doc.select("div.ltzd_body").first();
		if(firstDiv!=null){
			Element firstA = firstDiv.select("div.ltzd_L h2").first();
			if (firstA!=null){author =firstA .text();}
			date = DateUtils.matchDate(firstDiv.select("div.ltzd_R_t").text());
			content = HtmlCleaner.getContentHtml(url, firstDiv.select("div.ltzd_R_m"));
		}
		String rootid = StringUtils.replace(StringUtils.substringAfterLast(url, "/"), ".shtml", "");
		if(StringUtils.isNotBlank(rootid)){
			String updateUrl = "http://www.linkshop.com.cn/club/countjs.aspx?boardid=2&rootid="+rootid;
			String upHtml = CrawlHTML.GetHtml(updateUrl);
			if(upHtml!=null){
				clickNum = NumberUtils.matchNumber(StringUtils.substringAfter(upHtml, "write"));
				commentNum = NumberUtils.matchNumber(StringUtils.substringBetween(upHtml, "hf=", ";"));
			}
		}
		if(StringUtils.isBlank(title)){
		}
		bbs.setClickNum(clickNum);
		bbs.setCommentNum(commentNum);
		bbs.setTitle(StringUtils.trimSpace(title));
		bbs.setContent(content);
		bbs.setDate(date);
		bbs.setAuthor(author);
		bbs.setUpdateUrl(url);
		return bbs;
	}
	
	public NewsMeta Update(NewsMeta meta) {
		String url = meta.getUpdateUrl();
		if (StringUtils.isNotBlank(url)){
			UrlMeta urlMeta = CrawlHTML.responseToURL(url);
			return parserHtml(urlMeta);
		}
		return null;
	}
    
	
}
